#include "ClientCommunicator.hpp"
#include "Defines.hpp"

ClientCommunicator::ClientCommunicator()
{
	m_client = new Client;

	m_client->SetPort(100);
	m_client->SetIP("127.0.0.1"); // my ip
	m_client->Connect();

}

ClientCommunicator::~ClientCommunicator()
{
	if(m_client)
	{
		NullDelete(m_client);
	}
}

void ClientCommunicator::UpdateCharacter(const Character& character)
{
	string netMessage;

	// ID
	netMessage.append(GetString(character.ID()));
	netMessage.append("$");

	// X
	netMessage.append(GetString(character.GetX()));
	netMessage.append("$");

	// Y
	netMessage.append(GetString(character.GetY()));
	netMessage.append("$");

	// xVel
	netMessage.append(GetString(character.GetVelocity().x));
	netMessage.append("$");

	// yVel
	netMessage.append(GetString(character.GetVelocity().y));
	netMessage.append("$");

	SmallMessage message;
	message.id = ID_UPDATE_LOCATION;
	strcpy(message.str, netMessage.c_str());
	m_client->Send((const char*) &message);
}
void ClientCommunicator::AddCharacter(const Character& character)
{
	string netMessage;

	// X
	netMessage.append(GetString(character.GetX()));
	netMessage.append("$");

	// Y
	netMessage.append(GetString(character.GetY()));
	netMessage.append("$");

	// xVel
	netMessage.append(GetString(character.GetVelocity().x));
	netMessage.append("$");

	// yVel
	netMessage.append(GetString(character.GetVelocity().y));
	netMessage.append("$");

	SmallMessage message;
	message.id = ID_UPDATE_LOCATION;
	strcpy(message.str, netMessage.c_str());
	m_client->Send((const char*) &message);
}

void ClientCommunicator::RemoveCharacter(const Character& character)
{
	// not yet in server
}

void ClientCommunicator::Resync()
{
	TinyMessage msg;
	msg.id = ID_RESYNC;
	string netMessage = "$$";
	strcpy(msg.str, netMessage.c_str());
	m_client->Send((const char*) &msg);

}

bool ClientCommunicator::RecieveUpdates()
{
	Packet* packet = m_client->GetIncomingPacket();

	if(packet == NULL)
		return false;

	if(packet->data[0] == ID_UPDATE_LOCATION)
	{
		int pos = 1;
		string netData;
		ParseData(pos, netData, packet->data);

		int ID = atoi(netData.c_str());

		ParseData(pos, netData, packet->data);
		int x = atoi(netData.c_str());

		ParseData(pos, netData, packet->data);
		int y = atoi(netData.c_str());

		Vector2D position;
		ParseData(pos, netData, packet->data);
		position.x = atof(netData.c_str());

		ParseData(pos, netData, packet->data);
		position.y = atof(netData.c_str());
		
		//EntityMgr->GetEntityFromID(ID)->ChangeX(x);
		//EntityMgr->GetEntityFromID(ID)->ChangeY(y);
		EntityMgr->GetEntityFromID(ID)->SetPos(position);

		cout << packet->data << endl;
	}

	if(packet->data[0] == ID_CHAT)
		m_chatlog_messages.push_back((char*)(packet->data + 1));


	m_client->KillPacket(packet);

	return true; // a message was recieved; there might be another one
}